<?php
// +----------------------------------------------------------------------
// | najing 接收测试
// +----------------------------------------------------------------------
// | Author: huangzhen
// +----------------------------------------------------------------------

namespace app\cardeadmin\controller;

use app\api\controller\EmailSend;
use app\common\controller\AdminController;
use app\common\model\GetDemo;
use app\common\model\GetDemoTwo;
use app\common\model\ManageLog;
use app\common\model\Notice;
use app\common\model\NoticeIndex;
use app\common\model\UserIp;
use app\common\model\UserPay;
use app\common\model\UserSet;
use app\common\model\UserSetLog;
use think\facade\Db;
use think\facade\View;
use app\api\controller\OssUp;

/**
 * accept
 * Class Setting
 * @package app\admin\controller
 */
class Server extends AdminController
{
    /**
     * 用户日志列表
     */
    public function index()
    {
        $logModel = new GetDemo();
        if ($this->request->isAjax()) {
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function notice()
    {
        if ($this->request->isAjax()) {
            $logModel = new Notice();
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function noticeDel()
    {
        $result = [
            'status' => false,
            'msg'    => '失败',
            'data'   => ''
        ];

        $id = input('post.id');
        $re = Db::name('notice')->where(['id' => $id])->delete();
        if ($re) {
            $result['status'] = true;
            $result['msg']    = '删除成功';
        } else {
            $result['msg'] = '删除失败，请重试';
        }

        return $result;

    }

    public function alipay()
    {
        if ($this->request->isAjax()) {
            $logModel = new UserPay();
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function alipayData()
    {
        if ($this->request->isAjax()) {
            $post = input('param.');
            $where =[];
            $where[] = ['status_check', '=', 1];

            if(isset($post['username']) && !empty($post['username'])){
                $user_id = Db::name('user')->where(['username'=>$post['username']])->value('id');
                $where[] = ['user_id', '=', $user_id];
            }
            if(isset($post['datetime']) && !empty($post['datetime'])){
                $time_list = explode('_' , $post['datetime']);
                $start_time = strtotime($time_list[0] . " 00:00:00");
                $end_time   = strtotime($time_list[1] . " 23:59:59");
                $where[] = ['ctime', 'between', "{$start_time},{$end_time}"];
            }else{
                $end_time   = strtotime(date("Y-m-d 23:59:59"));
                $start_time = strtotime(date("Y-m-d",strtotime("-30 day")) . " 00:00:00");
                $where[] = ['ctime', 'between', "{$start_time},{$end_time}"];
            }
            $list = Db::name('user_pay')
                ->field('from_unixtime(ctime + 15*60*60,"%Y-%m-%d") days,sum(amount) amount,sum(amount_en) amount_en')
                ->where($where)
                ->group('days')
                ->order('days desc')
                ->select()
                ->toArray();

            return $result = [
                'code'  => 0,
                'msg'   => lang('get info success'),
                'data'  => $list,
                'count' => count($list),
            ];
        }
        return  View::fetch();
    }

    public function noticeAdd()
    {
        if($this->request->isPost()) {
            $data   = input('param.');
            $list   = Db::name('notice')
                ->where(['title'=> trim($data['title'])])->find();
            if($list) return $this->err('标题已存在.');
            $insert = [
                'title'  => $data['title'],
                'text'   => $data['text'],
                'ctime'  => strtotime($data['datetime'])
            ];
            $re     = Db::name('notice')->save($insert);

            if($re){
                ManageLog::saveManageLog([
                    'manage_id' => $this->manage_id ,
                    'desc'      => 'Notice Add',
                    'content'   => ['title' => trim($data['title'])]
                ]);
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        $str = strtotime(date('Y-m-d H:i:s')) - 13*60*60;
        View::assign([
            'datetime'          =>  date('Y-m-d H:i:s',$str)
        ]);
        return View::fetch();
    }

    public function upload()
    {
         if ($this->request->isPost()){
            // 获取表单上传文件
            $file = $this->request->file('file');
             $suffix_list = explode("." , $file->getOriginalName());
             $suffix      = $suffix_list[1] ?? 'jpg';
             $result   = OssUp::fileUp([
                 'type'      => 'document',
                 'tmp_name'  => $file->getRealPath(),
             ],$suffix);
             $blog       = $result['blog'];
             $img_url    = $result['img_url'];
             if($blog){
                 $img_name_list = explode('/',$img_url);
                 $img_name      = !empty($img_name_list)? end($img_name_list):'';
                 return json([
                     'code'      => 0,
                     'data'      => [
                         'src'       => $img_url,
                         'title'     => $img_name
                     ],
                     'msg'       => '上传成功',
                 ]);
             }else{
                 return json([
                     'code'      => 1,
                     'msg'       => '上传失败'.$file->getError(),
                 ]);
             }
        }

//        if ($this->request->isPost()){
//            $res['code'] = 0;
//            $res['msg']  = "上传成功";
//            // 获取表单上传文件
//            $file = $this->request->file('file');
//            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'images');//保存路径
//            dd($info);
//            if ($info){
//                $res['data']['title']= $info->getFilename();
//                $filepath =$info->getSaveName();
//                $res['data']['src'] = "/uploads/images/".$filepath;
//            }else{
//                $res['code'] = 1;
//                $res['msg'] = '上传失败'.$file->getError();
//            }
//            return $res;
//        }
    }


    public function noticeEdit()
    {
        $model = new Notice();
        $id     = input('get.id');

        if($this->request->isPost()) {
            $data   = input('param.');
            $insert = [
                'set_id' => $data['set_id'],
                'title'  => $data['title'],
                'text'   => $data['text'],
                'ctime'  => strtotime($data['datetime'])
            ];
            $re     = $model->setEdit($insert);
            if($re){
                ManageLog::saveManageLog([
                    'manage_id' => $this->manage_id ,
                    'desc'      => 'Notice Edit',
                    'content'   => ['title' => $data['title']]
                ]);
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        $data= $model->find($id);
        View::assign([
            'data'          => $data,
            'datetime'      => date('Y-m-d H:i:s',$data['ctime'])
        ]);
        return View::fetch();
    }


    public function contactUs()
    {
        $logModel = new GetDemoTwo();
        if ($this->request->isAjax()) {
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function editRemark()
    {
        if($this->request->isPost()) {
            $data           = input('param.');
            $demo_id        = $data['demo_id'];
            $demo_type      = $data['demo_type'];
            $remark         = $data['remark'];
            if($demo_type == 1){
                $model = new GetDemo();
            }else{
                $model = new GetDemoTwo();
            }
            $re = $model->where(['id'=>$demo_id])->update(['remark'=>$remark]);

            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $type   = input('get.type');
        $id     = input('get.id');
        if($type == 1){
            $model = new GetDemo();
        }else{
            $model = new GetDemoTwo();
        }
        $list = $model->find($id);

        View::assign([
            'remark'    => $list['remark'],
            'email'     => $list['email'],
            'demo_id'   => $id,
            'demo_type' => $type
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function userIp()
    {
        $logModel = new UserIp();
        if ($this->request->isAjax()) {
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function userSet()
    {
        if ($this->request->isAjax()) {
            $request = input('param.');
            $logModel = new UserSet();
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function setUp()
    {
        if($this->request->isPost()) {
            $data           = input('param.');
            $id_array       = $data['id_array'];
            $rate_fund      = $data['rate_fund'];
            $rate_refund    = $data['rate_refund'];
            $open_amount    = $data['open_amount'];
            $all_set        = $data['all_set'];
            $card_set_list  = $data['list'];
            $new_card_set   =[];
            foreach ($card_set_list as $k_new=>$v_new){
                if(strlen($v_new)>0){
                    $new_card_set[$k_new] = $v_new;
                }
            }
            $blog = true;
            try {
                $id_array_list = explode(',' , $id_array);
                foreach ($id_array_list as $k=>$v){
                    if($v != 1 || $v != 2){
                        $list = Db::name('user_set')->where(['id'=>$v])->find();
                        $card_set = json_decode($list['card_set'] , true);
                        $new_1 = [];
                        $new   = [];
                        foreach($card_set as $k_b=>&$v_b){
                            $bank_type              = $v_b['bank_type'];
                            $card_type              = $v_b['card_type'];
                            $new_1['bank_type']     = $bank_type;
                            $new_1['card_type']     = $card_type;
                            $is_used = $v_b['is_used'];
                            if(strlen($all_set)>0){
                                $is_used = $all_set;
                            }else{
                                if(isset($new_card_set[$card_type])){
                                    $is_used = $new_card_set[$card_type];
                                }
                            }
                            $new_1['is_used']       = $is_used;
                            $new_1['is_refe']       = $v_b['is_refe'];
                            $new_1['rate_tran']     = $v_b['rate_tran'];
                            $new_1['rate_fund']     = empty($rate_fund) ? $v_b['rate_fund'] : $rate_fund;
                            $new_1['rate_refund']   = empty($rate_refund) ? $v_b['rate_refund'] : $rate_refund;
                            $new_1['open_amount']   = empty($open_amount) ? $v_b['open_amount'] : $open_amount;

                            $new[] = $new_1;
                        }
                        Db::name('user_set')->where(['id'=>$v])->update(['card_set'=> json_encode($new)]);
                    }
                }
            }catch (\Exception $e){
                $blog = false;
            }
            if($blog){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }
        $user_set_list = Db::name('user_set')->where(['id'=>1])->find();
        $card_set_list = json_decode($user_set_list['card_set'] ,true);
        $card_type = [];
        foreach ($card_set_list as $k_set => $v_set){
            $card_type[] = $v_set['card_type'];
        }

        $id_array = input('get.id_array');
        View::assign([
            'card_type_list' => $card_type,
            'id_array'   => $id_array
        ]);
        View::layout(false);

        return [

            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function userSetLog()
    {
        if ($this->request->isAjax()) {
            $request = input('param.');
            $logModel = new UserSetLog();
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function cardSet()
    {
        if ($this->request->isAjax()) {
            $request  = input('param.');
            $logModel = new UserSet();
            $result   = $logModel::changeCardSet($request + ['manage_id' => $this->manage_id ]);
            if($result){
                return $this->scs('更新成功.');
            }else{
                return $this->scs('更新失败.');
            }
        }
        $id     = input('get.id');
        $list   = Db::name('user_set')->where(['id' => $id])->find();
        $card_set = json_decode($list['card_set'] , true);
        View::assign([
            'set_id'            => $id,
            'list'              => $card_set,
            'max_card'          => $list['max_card'],
            'zero_auth'          => $list['zero_auth'],
            'declined'          => $list['declined'],
            'facebook'          => $list['facebook']
        ]);
        return  View::fetch();
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function editMax()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $set_id     = $data['set_id'];
            $card_556766= $data['card_556766'] ?? '';
            $card_558068= $data['card_558068'] ?? '';
            $card_531847= $data['card_531847'] ?? '';
            $card_556766_new= $data['card_556766_new'] ?? '';
            $save_data  = [
                'max_card'      => trim($data['max_card']),
                'rate'          => trim($data['rate']),
                'refund_rate'   => trim($data['refund_rate']),
                'open_556735'   => trim($data['open_556735']),
                'open_556305'   => trim($data['open_556305']),
                'open_556766'   => trim($data['open_556766']),
                'open_558068'   => trim($data['open_558068']),
                'open_531847'   => trim($data['open_531847']),
                'open_556766_new'   => trim($data['open_556766_new']),
            ];
            $set_list   = Db::name('user_set')->find($set_id);
            $card_array = $set_list['card_array'];
            $card_array = explode(',' , $card_array);
            if(!empty($card_556766)){
                if(!in_array('556766' , $card_array))
                    array_push($card_array , '556766');
            }else{
                if(in_array('556766' , $card_array)){
                    $key = array_search('556766', $card_array);
                    unset($card_array[$key]);
                }
            }
            if(!empty($card_556766_new)){
                if(!in_array('556766_new' , $card_array))
                    array_push($card_array , '556766_new');
            }else{
                if(in_array('556766_new' , $card_array)){
                    $key = array_search('556766_new', $card_array);
                    unset($card_array[$key]);
                }
            }
            if(!empty($card_558068)){
                if(!in_array('558068' , $card_array))
                    array_push($card_array , '558068');
            }else{
                if(in_array('558068' , $card_array)){
                    $key = array_search('558068', $card_array);
                    unset($card_array[$key]);
                }
            }
            if(!empty($card_531847)){
                if(!in_array('531847' , $card_array))
                    array_push($card_array , '531847');
            }else{
                if(in_array('531847' , $card_array)){
                    $key = array_search('531847', $card_array);
                    unset($card_array[$key]);
                }
            }
            $card_array = implode(',' , $card_array);
            $save_data  += ['card_array' => $card_array];
            $re         = Db::name('user_set')->where(['id' => $set_id])
                            ->update($save_data);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $set_id = input('get.set_id');
        $list   = Db::name('user_set')->where(['id' => $set_id])->find();

        $card_556766= 0;
        $card_558068= 0;
        $card_531847= 0;
        $card_556766_new= 0;

        $card_array = $list['card_array'];
        $card_array = explode(',',$card_array);
        if(in_array('556766' , $card_array)){$card_556766= 1;}
        if(in_array('556766_new' , $card_array)){$card_556766_new= 1;}
        if(in_array('558068' , $card_array)){$card_558068= 1;}
        if(in_array('531847' , $card_array)){$card_531847= 1;}
        View::assign([
            'set_id'            => $set_id,
            'list'              => $list,
            'card_556766'       => $card_556766,
            'card_558068'       => $card_558068,
            'card_531847'       => $card_531847,
            'card_556766_new'   => $card_556766_new
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function sendEmail()
    {
        if ($this->request->isAjax()) {
            $request = input('param.');
            $title   = $request['title'];
            $desc    = $request['desc'];
            $no_send = $request['no_send'];

            $where   = "1=1 ";
            if(!empty($no_send)){
                $where .= " and username not in ('{$no_send}')";
            }
            $user_list = Db::name('user')->where($where)
                ->field('username')->select()->toArray();

            $email_array = '';
            $email_data  = '';
            try {
                 foreach ($user_list as $v){
                     $email_array .= $v['username'] . ',';
                     $email_data  .= $v['username'] . ';';
                 }

                $data = [];
                $data['email']  = trim($email_array , ',');
                $data['desc']   = $desc;
                $data['title']  = $title;
                EmailSend::sendEmail('all_user_send',$data);
                return $this->scs('success' , '',trim($email_data , ';'));
            } catch (\Exception $e) {
                $msg = $e->getMessage();
                return $this->err('error:' . $msg);
            }
        }
        return  View::fetch();
    }

    public function showDetail()
    {
        $id     = input('get.id');
        $list  = Db::name('user_pay')->where(['id' => $id])->find();

        View::assign([
            'response'      => $list['notify_desc'],
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function showUserSet()
    {
        $id     = input('get.id');
        $type   = input('get.type');
        switch ($type){
            case "change":
                $list  = Db::name("user_set_log")->where(['id' => $id])->find();
                $response = $list['data'];
                break;
            default:
                $list  = Db::name("user_set")->where(['id' => $id])->find();
                $response = $list['card_set'];
                break;

        }
        View::assign([
            'response'      => $response,
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function noticeIndex()
    {
        if ($this->request->isAjax()) {
            $logModel = new NoticeIndex();
            $request = input('param.');
            return $logModel->tableDataAdmin($request);
        }
        return  View::fetch();
    }

    public function noticeIndexAdd()
    {
        if($this->request->isPost()) {
            $data   = input('param.');
            $insert = [
                'text'   => $data['text'],
                'ctime'  => strtotime($data['datetime'])
            ];
            $re     = Db::name('notice_index')->save($insert);

            if($re){
                ManageLog::saveManageLog([
                    'manage_id' => $this->manage_id ,
                    'desc'      => 'Notice(首页弹框) Add',
                    'content'   => ['text'   => trim(substr($data['text'],0,50))]
                ]);
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        $str = strtotime(date('Y-m-d H:i:s')) - 13*60*60;
        View::assign([
            'datetime'          =>  date('Y-m-d H:i:s',$str)
        ]);
        return View::fetch();
    }

    public function noticeIndexEdit()
    {
        $model = new NoticeIndex();
        $id     = input('get.id');

        if($this->request->isPost()) {
            $data   = input('param.');
            $re = Db::name('notice_index')
                ->where(['id'=>$data['set_id']])
                ->update([
                    'text'   => $data['text'],
                    'ctime'  => strtotime($data['datetime'])
                ]);
            if($re){
                ManageLog::saveManageLog([
                    'manage_id' => $this->manage_id ,
                    'desc'      => 'Notice(首页弹框) Edit',
                    'content'   => ['text'   => trim(substr($data['text'],0,50))]
                ]);
                return $this->scs('add success');
            }else{
                return $this->err('add error');
            }
        }
        $data= $model->find($id);
        View::assign([
            'data'          => $data,
            'datetime'      => date('Y-m-d H:i:s',$data['ctime'])
        ]);
        return View::fetch();
    }

    public function noticeIndexDetail()
    {
        $list  = Db::name('notice_index')->order('id desc')->find();
        View::assign([
            'text'          => $list['text'],
        ]);
        View::layout(false);
        return View::fetch();
    }
}